﻿/*
// Exepack.NET 
// http://www.codeplex.com/exepack
//
// Assembly probing helper
// Written by Y [01-03-09]
// Copyright (c) 2008-2010 Alexey Yakovlev
*/

using System;
using System.Reflection;
using System.Collections.Generic;
using Mono.Cecil;

namespace Exepack
{
	/// <summary>
	/// Assembly resolver based on Mono.Cecil resolver
	/// </summary>
	public class AssemblyResolver : BaseAssemblyResolver
	{
		private IDictionary<string, AssemblyDefinition> Assemblies { get; set; }

		public AssemblyResolver()
		{
			Assemblies = new Dictionary<string,AssemblyDefinition>();
		}

		public Assembly Resolve(AssemblyName name)
		{
			var nameRef = new AssemblyNameReference(name.Name, name.CultureInfo.ToString(), name.Version);
			var asmDef = Resolve(nameRef);
			if (asmDef == null)
				return null;

			return Assembly.LoadFrom(asmDef.MainModule.Image.FileInformation.FullName);
		}

		public override AssemblyDefinition Resolve(AssemblyNameReference name)
		{
			if (!Assemblies.ContainsKey(name.Name))
			{
				var asm = base.Resolve(name);
				asm.Resolver = this;
				Assemblies[name.Name] = asm;
			}

			return Assemblies[name.Name];
		}
	}
}
